# -*- coding: utf-8 -*-
# @description: 
# @File  : demo2.py
# @Time  :2022-09-17 20:20:37
# @Author:selfeasy
# @Email :selfeasy@qq.com
import base64
from cryptography.hazmat.primitives import hashes,serialization
from cryptography.hazmat.primitives.asymmetric import padding,rsa
from cryptography.hazmat.backends import default_backend
print(default_backend())

private_key = rsa.generate_private_key(public_exponent=65537,key_size=2048,
backend=default_backend())
public_key = private_key.public_key()

print(private_key)
print(public_key)

def store_pem(private_key):
    pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format = serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    with open('./data/2p.pem', 'wb') as f:
        f.write(pem)

    punpem = public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo)
    with open('./data/2pub.pem', 'wb') as f:
        f.write(punpem)

store_pem(private_key)

private_key =serialization.load_pem_private_key(
    open('./data/2p.pem', 'rb').read(),
    password=None,backend=default_backend()
    )

public_key =serialization.load_pem_public_key(
    open('./data/2pub.pem', 'rb').read(),
    backend=default_backend()
    )
a=b'1663310078+208156836658167809+aaaaa201'
encrypt_data = public_key.encrypt(
    a,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None)
    )
print("encrypt data:", base64.b64encode(encrypt_data))



token = "gBp3qrkeWrOH0iDxP+p0ZTC4Qv31kvnhpK/s7vrRihmO7Fy46POAMKvNJblHIrX+kfB9Laxiv9O/iDP0aNJe6UYpc8k32WFeoTSgho2VeA0kYRAVO4Q+KXReBuk9VkB64IPiCy7jArD5XuantlJOkpOEpQGtYYphMh7d5N0cBQM=";
# encrypt_data = base64.b64decode(token)
print('token:',encrypt_data)
original_data = private_key.decrypt(
    encrypt_data,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)
print("Original data:", original_data)